package com.study.talk.ui.app.change

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.study.talk.data.model.vo.PasswordVo
import com.study.talk.ui.app.base.BaseViewModel
import com.study.talk.utils.extras.useless
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ChangePwdViewModel @Inject constructor(application: Application) :
    BaseViewModel(application) {

    val oldPwd = MutableLiveData<String>()
    val newPwd = MutableLiveData<String>()

    val complete = MutableLiveData(false)

    private fun check(): Boolean {
        if (oldPwd.value?.useless(app, "旧密码不能为空") == true) return false
        if (newPwd.value?.useless(app, "新密码不能为空") == true) return false
        if (newPwd.value?.length!! < 8) {
            showToast("新密码长度不能小于8位数")
            return false
        }
        return true
    }

    fun submit() {
        if (!check()) return
        viewModelScope.launch {
            if (userRepository.updatePwd(
                    passwordVo = PasswordVo(oldPwd.value, newPwd.value),
                    fail = {
                        it?.let { showToast(it) }
                    })){
                showToast("密码修改成功")
                complete.postValue(true)
            }else{
                showToast("密码修改失败")
                complete.postValue(true)
            }
        }
    }
}